﻿namespace Blaze.UI
{
    using System.Collections;
    using Framework;
    using UnityEngine;
    using UnityEngine.Assertions;

    /// <summary>
    /// 精灵表动画组件。
    /// </summary>
    public class AnimatedSpriteSheet : MonoBehaviour
    {
        public int Column;
        public int FPS = 10;
        public int Row;

#if UNITY_EDITOR

        private void Awake()
        {
            CoroutineManager.Initialize();
        }

#endif

        private void OnDisable()
        {
            if (mCoroutine != null)
            {
                CoroutineManager.Stop(mCoroutine);
                mCoroutine = null;
            }
        }

        private void OnEnable()
        {
            if (mMaterial == null)
                return;
            mCoroutine = CoroutineManager.StartNew(run());
        }

        private IEnumerator run()
        {
            while (true)
            {
                mIndex++;
                mIndex = mIndex%(Row*Column);
                var row = mIndex/Column;
                var offset = new Vector2((float) mIndex/Column - row, (float) (Row - row - 1)/Row);
                yield return YielderFactory.WaitForSeconds(1.0f/FPS);
                mMaterial.SetTextureOffset("_MainTex", offset);
            }
        }

        private void Start()
        {
            Assert.IsTrue(FPS > 0);
            var r = GetComponent<Renderer>();
            if (r == null)
            {
                enabled = false;
                return;
            }
            mMaterial = r.material;
            var size = new Vector2(1f / Column, 1f / Row);
            mMaterial.SetTextureScale("_MainTex", size);
            mCoroutine = CoroutineManager.StartNew(run());
        }

        private int mIndex;

        private Material mMaterial;
        private Coroutine mCoroutine;
    }
}